//login & register
const express = require('express')
const router = express.Router()
// 使用方法再npm里面看  https://www.npmjs.com/package/bcrypt
const bcrypt = require('bcrypt')
// 使用方法再npm里面看  https://www.npmjs.com/package/gravatar
const gravatar = require('gravatar')
// 使用方法再npm里面看     https://www.npmjs.com/package/jsonwebtoken
const jwt = require('jsonwebtoken')
const User = require('../../model/User.js')
const keys = require('../../config/keys.js')
const passport = require('passport')

router.get('/test',(req,res)=>{
  res.json({msg:'login worker'})
})

router.post('/register',(req,res)=>{
  // console.log(req.body);
  // 查询数据库中是否拥有邮箱
  User.findOne({email:req.body.email}).then((user)=>{
     if(user){
       return res.status(400).json('邮箱已被注册!')
     }else{
      var avatar = gravatar.url(req.body.email, {s: '200', r: 'pg', d: 'mm'});
       const newUser = new User({
         name:req.body.name,
         email:req.body.email,
         avatar, 
         password:req.body.password,
         identity:req.body.identity
       })
      //  加密
       bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(newUser.password, salt, function(err, hash) {
           if(err) throw err
           newUser.password = hash
          newUser.save().then(user => res.json(user)).catch(err=>console.log(err))
        });
    });

  
     }
   })
})

// $route  Post api/users/login
//@desc  返回token jwt passport
//@access public
router.post('/login',(req,res) => {
  // const email = req.body.email
  // const password = req.body.password
  // 查询数据库
  User.findOne({email:req.body.email}).then(user=>{
    if(!user){
      // res.send(user)
      return  res.status(404).json('用户不存在')
    }
    // 密码匹配
    bcrypt.compare(req.body.password, user.password).then(isMatch=>{
      if(isMatch){
        const rule = {id:user.id,name:user.name,avatar:user.avatar,identity:user.identity};
      // jwt.sign('规则',"加密名字",'{过期时间：秒}','箭头函数')
        jwt.sign(rule,keys.secretOrkey,{expiresIn:3600},(err,token)=>{
        if(err) throw err
        res.json({
          sucess:'true',
          token:"Bearer " + token
        })
      })
      }else{
        return res.status(400).json('密码错误')
      }
    })
  })
})


//$router Get api/users/current
//@desc return current user
//@access Private

router.get('/current',passport.authenticate('jwt',{session:false}),(req,res)=>{
  // 发送给客户端的不可以是全部的req.user,因为带上了密码
    res.json({
      id:req.user.id,
      name:req.user.name,
      email:req.user.email,
      identity:req.user.identity
    })
})



module.exports = router